package cn.com.self.apis.portal.controller;

import cn.com.self.apis.portal.util.EhcacheUtil;
import cn.com.selfsoft.smartcity.commons.http.ResultModel;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.*;

/**
 * @author
 * @date：2020/2/21
 **/
@RestController
@RequestMapping("/wx")
public class LoginController   {


    /**
     * 通过用户登录Code获取用户的openid
     *
     * @param loginCode
     * @return
     */
    public static Map<String, Object> getOpenidByCode(String loginCode) {

        String getOpenidUrl = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, Object> param = new HashMap<>();
        param.put("appid", "wxdea23643df74d842");
        param.put("secret", "d4d1215526d2904c6399e5ea8bf0fa82");
        param.put("grant_type", "authorization_code");
        param.put("js_code", loginCode);
        String result = HttpUtil.get(getOpenidUrl, param);
        System.out.println(result);

        JSONObject myJson = JSONObject.parseObject(result);
        Map<String, Object> map = (Map<String, Object>) myJson;
        String openid = myJson.getString("openid");
        String session_key = myJson.getString("session_key");
        EhcacheUtil.getInstance().put("user", openid, session_key);
        return map;
    }

    /**
     * 获取access_token
     *
     * @return
     */
    public static String getAccessToken() {

        String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxdea23643df74d842&secret=d4d1215526d2904c6399e5ea8bf0fa82";
        String result = HttpUtil.get(getAccessTokenUrl);
        System.out.println(result);

        JSONObject myJson = JSONObject.parseObject(result);
        String openid = myJson.getString("openid");

        return openid;
    }

    /**
     * 小程序登录接口
     *
     * @param code
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestParam String code) {
        Map<String, Object> map = getOpenidByCode(code);
        if (null == map) {
            return ResponseEntity.status(HttpStatus.OK).body(new ResultModel<>("获取openid失败"));
        }
        map.put("session_time", new Date());
//        Long userId = addPublicUser(json);
//        UserOpenid uo = getUserOpenidByOpenid(openid);

//        if (null == uo) {
//            UserOpenid userOpenid = new UserOpenid();
//            userOpenid.setStatus("1");
//            userOpenid.setRegisterSource("wx");
////            userOpenid.setUserId(userId);
//            userOpenid.setOpenid(openid);
//            wxOpenidService.create(userOpenid);
//        }

        return ResponseEntity.status(HttpStatus.OK).body(new ResultModel<>(map));

    }

    /**
     * 小程序解密个人信息接口
     *
     * @param json
     * @return
     */
    @RequestMapping(value = "/decodeInfo")
    public ResponseEntity decodeUserInfo(@RequestBody JSONObject json) {

        String encryptedData = json.getString("encryptedData");;
        String iv = json.getString("iv");;
        String openId = json.getString("openId");;
        //从缓存中获取session_key
        String sessionkey = (String) EhcacheUtil.getInstance().get("user", openId);
        if (StringUtils.isEmpty(sessionkey)) {
            return ResponseEntity.status(HttpStatus.OK).body(new ResultModel<>("sessionkey为空"));
        }
        try {
            encryptedData = URLEncoder.encode(encryptedData, "UTF-8").replace("%3D", "=").replace("%2F", "/");
            iv = URLEncoder.encode(iv, "UTF-8").replace("%3D", "=").replace("%2F", "/");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String userInfo = getUserInfo(encryptedData, sessionkey, iv);
        return ResponseEntity.status(HttpStatus.OK).body(new ResultModel<>(userInfo));
    }

    public String getUserInfo(String encryptedData, String sessionkey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.decodeBase64(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decodeBase64(sessionkey);
        // 偏移量
        byte[] ivByte = Base64.decodeBase64(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                System.out.println(result);
                return result;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 小程序退出登录接口
     *
     * @param openId
     * @return
     */
    @PostMapping("/logout")
    public ResponseEntity logout(@RequestParam String openId) {
        String sessionkey = (String) EhcacheUtil.getInstance().get("user", openId);
        if (StringUtils.isNotBlank(sessionkey)) {
            EhcacheUtil.getInstance().remove("user", openId);
        }
        return ResponseEntity.status(HttpStatus.OK).body(new ResultModel<>("用户已退出登录"));
    }

    /**
     * 小程序是否登录接口
     *
     * @param openId
     * @return
     */
    @PostMapping("/status")
    public ResponseEntity status(@RequestParam String openId) {
        String sessionkey = (String) EhcacheUtil.getInstance().get("user", openId);
        if (StringUtils.isNotBlank(sessionkey)) {
            return ResponseEntity.status(HttpStatus.OK).body(new ResultModel<>(1));
        }else {
            return ResponseEntity.status(HttpStatus.OK).body(new ResultModel<>(0));
        }

    }



}
